/*
       Author: Nathan Newman 
       File Name: dir.c
       Purpose: Display the MPX process file contents of directory
       Last update: 09/12/2011 

*/

#include "mpx_supt.h"
#include "commhand.h"
#include "dir.h"

int getDir(char args[MAX_NARGS][MAX_ARGLEN], int nargs){
	int eCode, lineCnt = 0, inc = 1;
	long fSize;
	char dName[MAX_DNAME];
	if(nargs<1) return 0;
	if(strcmp(args[0],"DIR")!=0 && strcmp(args[0],"LS")!=0 && strcmp(args[0],"DIRECTORY")!=0) return 0;
	if(nargs>2){
		printf("Error: Improper Command Syntax\nUsage: %s <directory name>\n",args[0]); 
		return 1;
	}
  if(nargs==1) eCode = sys_open_dir(NULL);
	else eCode = sys_open_dir(args[1]);
	switch (eCode){
		
		case 0:
			eCode = sys_get_entry(dName,MAX_DNAME,&fSize);
			if(eCode==ERR_SUP_NOENTR) {
				printf("(empty directory)\n");
				break;
			}
			printf("File Name\tFile Size (bytes)\n");
			while(eCode != ERR_SUP_NOENTR && !pager(&lineCnt,inc)){
				switch (eCode){
					case 0:	
						printf("%s\t%ld\n",dName,fSize);
						eCode = sys_get_entry(dName,MAX_DNAME,&fSize);
						break;
					case ERR_SUP_DIRNOP:
						printf("Error: no directory is open for reading\n");
						eCode = ERR_SUP_NOENTR;
						break;
					case ERR_SUP_RDFAIL:
						printf("Error: unable to read from directory\n");
						eCode = ERR_SUP_NOENTR;
						break;
					case ERR_SUP_NAMLNG:
						printf("Debug: directory name is too long\n");
						eCode = ERR_SUP_NOENTR;
						break;
					default :
						printf("Error: a problem occurred while displaying the directory files\n");
						eCode = ERR_SUP_NOENTR;
						break;
				}
			} 
			break; //end case 0
		
		case ERR_SUP_INVDIR:
			printf("Error: unrecognized directory name\n");
			break;
		case ERR_SUP_DIROPN:
			printf("Error: a problem occurred opening the specified directory\n");
			break;
		default:
			printf("Error: unable to open directory");
			break;
	}
	eCode=sys_close_dir();
	if(eCode!=0) printf("Error: a problem occurred closing the directory");
	return 1;
}